<?php

namespace app\common\model\service;

use app\common\model\BaseModel;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibMemberDistribute;
use app\common\model\hfztcy\LibOrderOneYuan;
use app\common\model\hfztcy\LibOrderRedMother;
use app\common\model\hfztcy\LibOrderVip;
use app\common\model\hfztcy\LibOrderVipAuth;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibUserVideoAuth;
use app\common\model\hfztcy\LibVideoAuth;
use app\common\model\hfztcy\LibVip;
use app\common\model\LibAdmin;
use app\common\model\LibUser;
use common\Common;
use think\Db;
use think\Exception;

//公共函数

//{"title":"红娘视频认证收费模式","amount":"398","red_mother_direct":"0.4","red_mother_indirect":"0.1","city":"0.05","district":"0.05","customer":"0.05","train":"0.05"}
//{"title":"视频认证收费模式","amount":"398","red_mother_direct":"0.4","red_mother_indirect":"0.1","store":"0.2","city":"0.05","district":"0.05","customer":"0.05","train":"0.05"}
//{"title":"单次付费查看视频","direct_user":"0.5","private_red_mother":"0.2","store":"0.2","city":"0.05","district":"0.05"}
//{"title":"vip收费模式","city":"0.05","district":"0.05"}

/**
 * 异步支付
 * @name LibOrder.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibOrder extends BaseModel
{
    public $input;
    public $user;
    private $userModel;

    public function __construct($user)
    {
        $this->input = input();
        $this->user = $user;
        $this->userModel = new LibUser();
        parent::__construct();
    }

    // {"title":"视频认证收费模式","amount":"999",
    //"red_mother_direct":"0.3",
    //"store_point_user":"0.1",
    //"red_mother_indirect":"0.1",
    //"store":"0.1",
    //"store_direct_user":"0.1",
    //"city":"0.05",
    //"district":"0.05",
    //"customer":"0.05",
    //"train":"0.05"}

    /**
     * Info: 直推用户【红娘认证】【视频认证】
     * Date: 2022/11/18 9:58
     */
    private function getDirectUser($configValue, $args, $memberDistributeModel, $key)
    {
        $fields = [];
        if (isset($configValue['red_mother_direct']) && $args['amount'] > 0) {
            $findDistributeRes = $memberDistributeModel->findMemberDistribute(['user_id' => $this->user['id']]);
            if ($findDistributeRes['errorCode'] == 0) {
                $direct_user_id = $findDistributeRes['data']['one_user_id'];
            } else {
                $direct_user_id = $this->user['parent_id'];
            }
            // 标识直推用户是否红娘身份
            $is_red_mother_identity = false;
            // 查询直推用户
            $findUserRes = $this->userModel->findUser(['id' => $direct_user_id]);
            if ($findUserRes['errorCode'] == 0) {
                // 判断用户是否红娘身份
                $identityByParentUser = $findUserRes['data']['identity'];
                if (strpos($identityByParentUser, '3') !== false) {
                    $is_red_mother_identity = true;
                }
            }
            // 是红娘身份，则记录分销奖励
            if ($key == 'red_mother_auth_rate') {//【红娘认证】
                $direct_user_rate = (float)$configValue['red_mother_direct'];//红娘直推分润比例
            } else {//【视频认证】
                if ($args['is_offline'] == 1) {//表示用户指定门店
                    $direct_user_rate = (float)$configValue['red_mother_direct'];//红娘直推分润比例
                } else {
                    $direct_user_rate = (float)$configValue['red_mother_direct'] + (float)$configValue['store_point_user'];//红娘直推分润比例
                }
            }
            // 直接推荐人是红娘的情况下，保存佣金到订单表中
            if ($is_red_mother_identity && $direct_user_rate) {
                $zt_commission_money = ($args['amount'] * $direct_user_rate);
                $zt_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $zt_commission_money), 0, -1));
                $fields['zt_commission_money'] = abs($zt_commission_money);
                $fields['direct_user_id'] = $direct_user_id;//保存直接推荐人到订单表中
            }
        }
        return $fields;
    }

    /**
     * Info: 间推用户【红娘认证】【视频认证】
     * Date: 2022/11/18 9:58
     */
    private function getIndirectUser($configValue, $args, $memberDistributeModel)
    {
        $fields = [];
        if (isset($configValue['red_mother_indirect']) && $args['amount'] > 0) {
            // 红娘分销关系
            $findDistributeRes = $memberDistributeModel->findMemberDistribute(['user_id' => $this->user['id']]);
            if ($findDistributeRes['errorCode'] == 0)
            {
                // 该用户的间推用户
                $indirect_user_id = $findDistributeRes['data']['two_user_id'];
                // 标识间推用户是否红娘
                $is_red_mother_identity = false;
                // 查询间推用户
                $findUserRes = $this->userModel->findUser(['id' => $indirect_user_id]);
                if ($findUserRes['errorCode'] == 0) {
                    //判断用户是否红娘身份
                    $identityByParentUser = $findUserRes['data']['identity'];
                    if (strpos($identityByParentUser, '3') !== false) {
                        $is_red_mother_identity = true;
                    }
                }
                // 是红娘身份，则记录分销奖励
                $red_mother_indirect = (float)$configValue['red_mother_indirect'];
                if ($is_red_mother_identity && $red_mother_indirect) {
                    $jt_commission_money = ($args['amount'] * $red_mother_indirect);
                    $jt_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $jt_commission_money), 0, -1));
                    $fields['jt_commission_money'] = abs($jt_commission_money);
                    $fields['indirect_user_id'] = $indirect_user_id;//保存简介推荐人到订单表中
                }
            }
        }
        return $fields;
    }

    /**
     * Info: 直推用户【单次付费看视频】
     * Date: 2022/11/18 9:58
     */
    private function getDirectUserBySeeVideo($configValue, $args)
    {
        $fields = [];
        if (!isset($configValue['direct_user'])) return $fields;
        $direct_user_rate = (float)$configValue['direct_user'];
        $direct_user_id = (int)$args['share_user_id'];
        if (isset($configValue['direct_user']) && $direct_user_id && $args['amount'] > 0 && $direct_user_rate) {
            $zt_commission_money = ($args['amount'] * $direct_user_rate);
            $zt_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $zt_commission_money), 0, -1));
            $fields['zt_commission_money'] = abs($zt_commission_money);
            $fields['direct_user_id'] = $direct_user_id;
        }
        return $fields;
    }

    /**
     * Info: 直推用户(专属红娘)【单次付费看视频】
     * Date: 2022/11/18 9:58
     */
    private function getPrivateRedMotherUser($configValue, $args)
    {
        $private_red_mother_id = 0;
        $fields = [];
        if (!isset($configValue['private_red_mother'])) return $fields;
        $direct_user_id = $args['share_user_id'];
        $private_red_mother_rate = (float)$configValue['private_red_mother'];//如果直接分享人是红娘身份，则拥有专属红娘比例
        if (isset($configValue['private_red_mother']) && $direct_user_id && $args['amount'] > 0 && $private_red_mother_rate) {
            $findUserRes = $this->userModel->findUser(['id' => $direct_user_id]);
            if ($findUserRes['errorCode'] == 0) {
                $identityByParentUser = $findUserRes['data']['identity'];
                if (strpos($identityByParentUser, '3') !== false) {//判断用户是否红娘身份
                    $private_red_mother_id = $direct_user_id;
                }
            }
            if ($private_red_mother_id) {
                $zs_commission_money = ($args['amount'] * $private_red_mother_rate);
                $zs_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $zs_commission_money), 0, -1));
                $fields['private_red_mother_id'] = $private_red_mother_id;
                $fields['zs_commission_money'] = abs($zs_commission_money);
            }
        }
        return $fields;
    }

    /**
     * Info: 门店【单次付费看视频】
     * Date: 2022/11/18 9:58
     */
    private function getStoreBySeeVideo ($configValue, $args)
    {
        $fields = [];
        if (!isset($configValue['store'])) return $fields;
        $store_rate = (float)$configValue['store'];
        if (isset($configValue['store']) && $store_rate) {
            $findUserRes = $this->userModel->findUser(['id' => $args['like_user_id']]);
            if ($findUserRes['errorCode'] == 0) {
                $identity = $findUserRes['data']['identity'];
                $identity = explode(',',$identity);
                $identity = array_map('intval',$identity);
                $identity_id = max($identity);
                $userVideoModel = new LibUserVideoAuth();
                $order_id = 0;
                if ($identity_id == 1) {//注册会员
                    $findUserVideoRes = $userVideoModel->findUserVideoAuth(['user_id' => $args['like_user_id'],'type' => 0]);
                    if ($findUserVideoRes['errorCode'] == 0) {
                        $order_id = $findUserVideoRes['data']['order_id'];
                    }
                }
                if ($identity_id == 2) {//VIP会员
                    $findUserVideoRes = $userVideoModel->findUserVideoAuth(['user_id' => $args['like_user_id'],'type' => 1]);
                    if ($findUserVideoRes['errorCode'] == 0) {
                        $order_id = $findUserVideoRes['data']['order_id'];
                    }
                }
                if ($order_id) {
                    $orderModel = new \app\common\model\hfztcy\LibOrder();
                    $findOrderRes = $orderModel->findOrder(['id' => $order_id]);
                    if ($findOrderRes['errorCode'] == 0) {
                        $store_id = $findOrderRes['data']['store_id'];
                        $storeModel = new LibStore();
                        $findStoreRes = $storeModel->findStore(['id' => $store_id]);
                        if ($findStoreRes['errorCode'] == 0) {
                            $store_user_id = $findStoreRes['data']['uid'];
                            $store_commission_money = ($args['amount'] * $store_rate);
                            $store_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $store_commission_money), 0, -1));
                            $fields['store_user_id'] = $store_user_id;
                            $fields['md_commission_money'] = abs($store_commission_money);
                        }
                    }
                }
            }
        }
        return $fields;
    }

    /**
     * Info: 市代理商【单次付费看视频】【红娘认证】【视频认证】【VIP套餐】
     * Date: 2022/11/18 9:44
     */
    private function getAgentByShi($configValue, $args, $adminModel, $city)
    {
        $fields = [];
        if (!isset($configValue['city'])) return $fields;
        $city_rate = (float)$configValue['city'];
        if (isset($configValue['city']) && $args['amount'] > 0 && $city_rate) {
            $findAdminCityRes = $adminModel->findAdmin(['group_id' => 3, 'is_area' => 0, 'city' => $city]);
            if ($findAdminCityRes['errorCode'] == 0) {
                $shi_admin_id = $findAdminCityRes['data']['id'];
                $shi_commission_money = ($args['amount'] * $city_rate);
                $shi_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $shi_commission_money), 0, -1));
                $fields['shi_admin_id'] = $shi_admin_id;
                $fields['shi_commission_money'] = abs($shi_commission_money);
            }
        }
        return $fields;
    }

    /**
     * Info: 区县代理商【单次付费看视频】【红娘认证】【视频认证】【VIP套餐】
     * Date: 2022/11/18 9:44
     */
    private function getAgentByXian($configValue, $args, $adminModel, $area)
    {
        $fields = [];
        if (!isset($configValue['district'])) return $fields;
        $district_rate = (float)$configValue['district'];
        if (isset($configValue['district']) && $args['amount'] > 0 && $district_rate) {
            $findAdminAreaRes = $adminModel->findAdmin(['group_id' => 3, 'is_area' => 1, 'area' => $area]);
            if ($findAdminAreaRes['errorCode'] == 0) {
                $xian_admin_id = $findAdminAreaRes['data']['id'];
                $xian_commission_money = ($args['amount'] * $district_rate);
                $xian_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $xian_commission_money), 0, -1));
                $fields['xian_admin_id'] = $xian_admin_id;
                $fields['xian_commission_money'] = abs($xian_commission_money);
            }
        }
        return $fields;
    }

    /**
     * Info: 客服部【红娘认证】【视频认证】
     * Date: 2022/11/18 9:46
     */
    private function getAdminByCustomer($configValue, $args, $adminModel)
    {
        $fields = [];
        if (!isset($configValue['customer'])) return $fields;
        $customer_rate = (float)$configValue['customer'];
        if (isset($configValue['customer']) && $args['amount'] > 0 && $customer_rate) {
            $findCustomerRes = $adminModel->findAdmin(['group_id' => 1]);
            if ($findCustomerRes['errorCode'] == 0) {
                $kf_admin_id = $findCustomerRes['data']['id'];
                $kf_commission_money = ($args['amount'] * $customer_rate);
                $kf_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $kf_commission_money), 0, -1));
                $fields['kf_admin_id'] = $kf_admin_id;
                $fields['kf_commission_money'] = abs($kf_commission_money);
            }
        }
        return $fields;
    }

    /**
     * Info: 培训部 【红娘认证】【视频认证】
     * Date: 2022/11/18 9:46
     */
    private function getAdminByTrain($configValue, $args, $adminModel)
    {
        $fields = [];
        if (!isset($configValue['train'])) return $fields;
        $train_rate = (float)$configValue['train'];
        if (isset($configValue['train']) && $args['amount'] > 0 && $train_rate) {
            $findTrainRes = $adminModel->findAdmin(['group_id' => 2]);
            if ($findTrainRes['errorCode'] == 0) {
                $px_admin_id = $findTrainRes['data']['id'];
                $px_commission_money = ($args['amount'] * $train_rate);
                $px_commission_money = (float)sprintf("%.2f", substr(sprintf("%.3f", $px_commission_money), 0, -1));
                $fields['px_admin_id'] = $px_admin_id;
                $fields['px_commission_money'] = abs($px_commission_money);
            }
        }
        return $fields;
    }

    /**
     * Info: 分销字段
     * Date: 2022/11/16 10:27
     */
    private function getDistributeField($memberModel, $args, $item_key)
    {
        // 当前用户
        $findCurUserRes = $memberModel->findMember(['user_id' => $this->user['id']]);
        $city = $area = '';
        if ($findCurUserRes['errorCode'] == 0) {
            $city = $findCurUserRes['data']['city'];//所在市
            $area = $findCurUserRes['data']['area'];//所在区县
        } else {
            $findUserRes = $this->userModel->findUser(['id' => $this->user['id']]);
            if ($findUserRes['errorCode'] == 0 && strpos($findUserRes['data']['identity'],'0') !== false) {
                $city = $findUserRes['data']['city'];//所在市
                $area = $findUserRes['data']['country'];//所在区县
            }
        }

        $fields = [];
        // 分销参数
        $adminModel = new LibAdmin();
        $configModel = new LibConfig();
        $memberDistributeModel = new LibMemberDistribute();
        $configRes = $configModel->findConfig(['item_key' => $item_key]);
        if ($configRes['errorCode'] == 0)
        {
            // 分销参数
            $configValue = json_decode($configRes['data']['item_value'], true);

            // 订单金额
            $args['amount'] = (float)$args['amount'];

            // 制作费
            if (isset($configValue['amount'])) {
                $amount = (float)$configValue['amount'];
                if ($args['amount'] <= $amount) {
                    return $fields;
                }
                $args['amount'] = $args['amount'] - $amount;
            }
            $total = 0;

            // 红娘直推[视频认证][红娘认证]
            $fields1 = $this->getDirectUser($configValue, $args, $memberDistributeModel, $item_key);
            if ($fields1) $total += $fields1['zt_commission_money'];

            // 红娘间推[视频认证][红娘认证]
            $fields2 = $this->getIndirectUser($configValue, $args, $memberDistributeModel);
            if ($fields2) $total += $fields2['jt_commission_money'];

            //直推用户[单次付费看视频]
            $fields3 = $this->getDirectUserBySeeVideo($configValue, $args);
            if ($fields3) $total += $fields3['zt_commission_money'];

            //专属红娘[单次付费看视频]
            $fields4 = $this->getPrivateRedMotherUser($configValue, $args);
            if ($fields4) $total += $fields4['zs_commission_money'];

            //门店[单次付费看视频]
            $fields10 = $this->getStoreBySeeVideo($configValue, $args);
            if ($fields10) $total += $fields10['md_commission_money'];

            //市代比例[VIP套餐收费][单次付费看视频][视频认证][红娘认证]
            $fields5 = $this->getAgentByShi($configValue, $args, $adminModel, $city);
            if ($fields5) $total += $fields5['shi_commission_money'];

            //区县代比例[VIP套餐收费][单次付费看视频][视频认证][红娘认证]
            $fields6 = $this->getAgentByXian($configValue, $args, $adminModel, $area);
            if ($fields6) $total += $fields6['xian_commission_money'];

            // 客服部比例[视频认证][红娘认证]
            $fields7 = $this->getAdminByCustomer($configValue, $args, $adminModel);
            if ($fields7) $total += $fields7['kf_commission_money'];

            // 培训部比例[视频认证][红娘认证]
            $fields8 = $this->getAdminByTrain($configValue, $args, $adminModel);
            if ($fields8) $total += $fields8['px_commission_money'];

            // 总部[所有]
            $fields9 = [];
            if ($args['amount']) {
                $pt_commission_money = $args['amount'] - $total;
                $fields9['pt_commission_money'] = $pt_commission_money;
            }

            return array_merge($fields1,$fields2,$fields3,$fields4,$fields5,$fields6,$fields7,$fields8,$fields9,$fields10);
        }

        return $fields;
    }

    /**
     * Info: 单次付费看视频支付前检查用户状态
     * Date: 2022/11/18 17:56
     */
    public function paymentBeforeCheckUserStateByOneYuan ()
    {
        $userInfo = $this->user;
        // 检查用户是否游客,普通会员身份
        $is_guest = false;
        $identity_list = explode(',', $userInfo['identity']);
        if ($identity_list) {
            foreach ($identity_list as $item) {
                if ($item > 1) {
                    $is_guest = true;
                    break;
                }
            }
        }
        if ($is_guest) {
            return Common::errorArray(1, '该用户可以观看视频，无须付费', false);
        }

        $orderModel = new \app\common\model\hfztcy\LibOrderOneYuan();
        $findOrderRes = $orderModel->findOrder("`user_id` = {$userInfo['id']} and `like_user_id` = {$this->input['like_user_id']} and `state` = 1");
        if ($findOrderRes['errorCode'] == 0) {
            return Common::errorArray(1, '该用户可以观看视频，无须付费', false);
        }

        $memberModel = new LibMember();
        // 如果是VIP套餐用户，检查VIP是否过期
        if (strpos($userInfo['identity'],'2') !== false) {
            $findUserRes = $memberModel->findMember(['user_id' => $userInfo['id']]);
            if ($findUserRes['errorCode'] == 0) {
                if ($findUserRes['data']['vip_open_time'] < time()) {
                    return Common::errorArray(1, 'VIP已过期', false);
                }
            }
        }

        // 检查观看的用户是否上传认证视频
        $findRes = $memberModel->findMember(['user_id' => $this->input['like_user_id']]);
        if ($findRes['errorCode'] == 0) {
            //$identity_list = explode(',',$findRes['data']['state']);
            if (!$findRes['data']['is_vip_video']) {
                return Common::errorArray(1, '该用户尚未上传认证视频', false);
            }
        }

        return Common::errorArray(0, '状态正常', true);
    }

    /**
     * Info: 创建一元订单
     * Date: 2022/11/16 8:39
     */
    public function addOrderByOneYuanSeeVideo()
    {
        $data = $this->input;
        $args['amount'] = 1;//金额
        $args['user_id'] = $data['user_id'];//用户
        $args['like_user_id'] = $data['like_user_id'];//被浏览用户
        $args['share_user_id'] = $data['share_user_id'];//直接分享人
        unset($data);

        // 检查用户是否游客,普通会员身份
        $is_guest = false;
        $identity_list = explode(',', $this->user['identity']);
        if ($identity_list) {
            foreach ($identity_list as $item) {
                if ($item > 1) {
                    $is_guest = true;
                    break;
                }
            }
        }
        if ($is_guest) {
            return Common::errorArray(1, '该用户可以观看视频，无须付费', false);
        }

        $memberModel = new LibMember();
        // 如果是VIP套餐用户，检查VIP是否过期
        if (strpos($this->user['identity'],'2') !== false) {
            $findUserRes = $memberModel->findMember(['user_id' => $this->user['id']]);
            if ($findUserRes['errorCode'] == 0) {
                if ($findUserRes['data']['vip_open_time'] < time()) {
                    return Common::errorArray(1, 'VIP已过期', false);
                }
            }
        }

        // 检查观看的用户是否上传认证视频
        $findRes = $memberModel->findMember(['user_id' => $args['like_user_id']]);
        if ($findRes['errorCode'] == 0) {
            //$identity_list = explode(',',$findRes['data']['state']);
            if (!$findRes['data']['is_vip_video']) {
                return Common::errorArray(1, '该用户尚未开通栏目认证', false);
            }
        }
        // 检查订单参数
        $oneYuanOrderModel = new LibOrderOneYuan();
        $checkRes = $oneYuanOrderModel->goCheck($args);
        if ($checkRes['errorCode'] == 1) {
            return Common::errorArray(1, $checkRes['errorInfo'], false);
        }

        // 分销处理
        $distributeFields = $this->getDistributeField($memberModel, $args, 'see_video_rate');

        // 创建订单
        $orderModel = new \app\common\model\hfztcy\LibOrder();
        $code = $orderModel->generateOrderNum();
        Db::startTrans();
        try {
            unset($args['share_user_id']);
            $findOrderRes = $orderModel->findOrder("transaction_id IS NULL AND user_id = {$this->user['id']} AND type = 0");
            if ($findOrderRes['errorCode'] == 0) {
                $order_id = $findOrderRes['data']['id'];
                $orderModel->updateOrder(['id'  => $order_id],[
                    'code' => $code,
                    'type' => 0,
                    'user_id' => $this->user['id'],
                ]);
            } else {
                $result = $orderModel->addOrder([
                    'code' => $code,
                    'type' => 0,
                    'user_id' => $this->user['id'],
                ]);
                $order_id = (int)$result['data'];
            }
            $findOneYuanRes = $oneYuanOrderModel->findOrder(['order_id' => $order_id,'user_id' => $this->user['id']]);
            if ($findOneYuanRes['errorCode'] == 0) {
                $oneYuanOrderModel->updateOrder(['order_id' => $order_id,'user_id' => $this->user['id']],array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'add_time' => Common::getTime(),
                ]));
            } else {
                $oneYuanOrderModel->addOrder(array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'add_time' => Common::getTime(),
                ]));
            }
            Db::commit();

            return Common::errorArray(0, '订单创建成功', $order_id);
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1, '订单创建失败' . $exception->getMessage(), false);
        }
    }

    /**
     * Info: 创建vip订单
     * Date: 2022/11/16 8:41
     */
    public function addOrderByVip()
    {
        $data = $this->input;
        $args['amount'] = $data['amount'];//金额
        $args['user_id'] = $data['user_id'];//用户
        $args['vip_id'] = $data['vip_id'];//套餐ID
        unset($data);
        // 检查用户是否注册
        $memberModel = new LibMember();
        $findRes = $memberModel->findMember(['user_id' => $args['user_id']]);
        if ($findRes['errorCode'] == 1) return Common::errorArray(1, '该用户尚未注册', false);
        if ($findRes['data']['audit_state'] == 0) return Common::errorArray(1, '您的资料正在审核中', false);
        if ($findRes['data']['audit_state'] == 2) return Common::errorArray(1, '您的资料审核未通过', false);
        // 检查用户身份
//        $identity_list = explode(',', $findRes['data']['state']);
//        if ($identity_list) {
//            foreach ($identity_list as $item) {
//                if ($item > 2) {
//                    return Common::errorArray(1, '该用户无须付费', false);
//                }
//            }
//        }
        // 检查VIP套餐
        $vipModel = new LibVip();
        $findVipRes = $vipModel->findVip(['id' => $args['vip_id']]);
        if ($findVipRes['errorCode'] == 1) {
            return Common::errorArray(1, 'VIP不存在', false);
        }
        // 检查订单参数
        $vipOrderModel = new LibOrderVip();
        $checkRes = $vipOrderModel->goCheck($args);
        if ($checkRes['errorCode'] == 1) {
            return Common::errorArray(1, $checkRes['errorInfo'], false);
        }

        // 分销处理
        $distributeFields = $this->getDistributeField($memberModel, $args, 'vip_model_rate');

        // 创建订单
        $orderModel = new \app\common\model\hfztcy\LibOrder();
        $code = $orderModel->generateOrderNum();
        Db::startTrans();
        try {
            $findOrderRes = $orderModel->findOrder("transaction_id IS NULL AND user_id = {$this->user['id']} AND type = 1");
            if ($findOrderRes['errorCode'] == 0) {
                $order_id = $findOrderRes['data']['id'];
                $orderModel->updateOrder(['id'  => $order_id],[
                    'code' => $code,
                    'type' => 1,
                    'user_id' => $this->user['id'],
                ]);
            } else {
                $result = $orderModel->addOrder([
                    'code' => $code,
                    'type' => 1,
                    'user_id' => $this->user['id'],
                ]);
                $order_id = (int)$result['data'];
            }
            $findVipOrderRes = $vipOrderModel->findOrder(['order_id' => $order_id,'user_id' => $this->user['id']]);
            if ($findVipOrderRes['errorCode'] == 0) {
                $vipOrderModel->updateOrder(['order_id' => $order_id,'user_id' => $this->user['id']],array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'amount' => $findVipRes['data']['price'],
                    'vip_info' => json_encode($findVipRes['data'], JSON_UNESCAPED_UNICODE),
                    'add_time' => Common::getTime(),
                ]));
            } else {
                $vipOrderModel->addOrder(array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'amount' => $findVipRes['data']['price'],
                    'vip_info' => json_encode($findVipRes['data'], JSON_UNESCAPED_UNICODE),
                    'add_time' => Common::getTime(),
                ]));
            }
            Db::commit();

            return Common::errorArray(0, '订单创建成功', $order_id);
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1, '订单创建失败' . $exception->getMessage(), false);
        }
    }

    /**
     * Info: 创建栏目认证订单
     * Date: 2022/11/16 8:48
     */
    public function addOrderByVipAuth()
    {
        $data = $this->input;
        $args['amount'] = $data['amount'];//金额
        $args['user_id'] = $data['user_id'];//用户
        $args['package_id'] = $data['package_id'];//套餐ID
        $args['is_offline'] = $data['is_offline'];//是否线下门店成交
        $args['store_id'] = isset($data['store_id']) ? $data['store_id'] : 0;//门店
        unset($data);
        if ($args['is_offline'] && $args['store_id'] == 0) return Common::errorArray(1, '请选择门店', false);
        // 检查用户是否注册
        $memberModel = new LibMember();
        $findRes = $memberModel->findMember(['user_id' => $args['user_id']]);
        if ($findRes['errorCode'] == 1) return Common::errorArray(1, '该用户尚未注册', false);
        if ($findRes['data']['audit_state'] == 0) return Common::errorArray(1, '您的资料正在审核中', false);
        if ($findRes['data']['audit_state'] == 2) return Common::errorArray(1, '您的资料审核未通过', false);
        // 检查用户身份 身份0游客1普通用户2vip用户3红娘4门店
        $identity_list = explode(',', $findRes['data']['state']);
        if ($identity_list) {
//            if (in_array(1, $identity_list)) {
//                if ($findRes['data']['is_vip_video']) {
//                    return Common::errorArray(1, '您已开通栏目认证', false);
//                }
//            }
//            if (in_array(2, $identity_list)) {
//                if ($findRes['data']['is_vip_video']) {
//                    return Common::errorArray(1, '您已开通栏目认证', false);
//                }
//            }
//            if (in_array(3, $identity_list)) {
//                if ($findRes['data']['is_vip_video']) {
//                    return Common::errorArray(1, '您已开通栏目认证', false);
//                }
//            }
        }
        $orderModel = new \app\common\model\hfztcy\LibOrder();
//        $findOrderRes = $orderModel->findOrder("transaction_id IS NOT NULL AND user_id = {$this->user['id']} AND type = 2");
//        if ($findOrderRes['errorCode'] == 0 && $args['package_id'] == 4) {
//            return Common::errorArray(1, '您已开通栏目认证', false);
//        }
        // 认证费用
        $configModel = new LibVideoAuth();
        $findRes = $configModel->findVideoAuth(['id' => $args['package_id']]);
        $vip_auth_fee = 0;
        if ($findRes['errorCode'] == 0) $vip_auth_fee = $findRes['data']['money'];
        if (bccomp($args['amount'], $vip_auth_fee) != 0) return Common::errorArray(1, '金额错误', false);
        $args['amount'] = $vip_auth_fee;
        $vip_auth_info = $findRes['data'];
        // 订单参数
        $vipAuthOrderModel = new LibOrderVipAuth();
        $checkRes = $vipAuthOrderModel->goCheck($args);
        if ($checkRes['errorCode'] == 1) return Common::errorArray(1, $checkRes['errorInfo'], false);

        // 分销处理
        $distributeFields = $this->getDistributeField($memberModel, $args, 'vip_video_auth_rate');

        // 创建订单
        $code = $orderModel->generateOrderNum();
        Db::startTrans();
        try {
            $store_arr = [];
            if ($args['store_id']) {
                $store_arr['store_id'] = $args['store_id'];
                $store_arr['distribute_time'] = Common::getTime();
            }
            $findOrderRes = $orderModel->findOrder("transaction_id IS NULL AND user_id = {$this->user['id']} AND type = 2");
            if ($findOrderRes['errorCode'] == 0) {
                $order_id = $findOrderRes['data']['id'];
                $orderModel->updateOrder(['id'  => $order_id],array_merge([
                    'code' => $code,
                    'type' => 2,
                    'user_id' => $this->user['id'],
                    'exec_state' => 0//待发放的冻结收益
                ],$store_arr));
            } else {
                $result = $orderModel->addOrder(array_merge([
                    'code' => $code,
                    'type' => 2,
                    'user_id' => $this->user['id'],
                    'exec_state' => 0//待发放的冻结收益
                ],$store_arr));
                $order_id = (int)$result['data'];
            }
            unset($args['store_id']);
            $findVipAuthOrderRes = $vipAuthOrderModel->findOrder(['order_id' => $order_id,'user_id' => $this->user['id']]);
            if ($findVipAuthOrderRes['errorCode'] == 0) {
                $vipAuthOrderModel->updateOrder(['order_id' => $order_id,'user_id' => $this->user['id']],array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'is_offline' => $args['is_offline'],
                    'package_id' => $args['package_id'],
                    'package_info' => json_encode($vip_auth_info,JSON_UNESCAPED_UNICODE),
                    'add_time' => Common::getTime(),
                ]));
            } else {
                $vipAuthOrderModel->addOrder(array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'is_offline' => $args['is_offline'],
                    'package_id' => $args['package_id'],
                    'package_info' => json_encode($vip_auth_info,JSON_UNESCAPED_UNICODE),
                    'add_time' => Common::getTime(),
                ]));
            }
            Db::commit();
            return Common::errorArray(0, '订单创建成功', $order_id);
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1, '订单创建失败' . $exception->getMessage(), false);
        }
    }

    /**
     * Info: 创建红娘认证
     * Date: 2022/11/16 8:53
     */
    public function addOrderByRedMotherAuth()
    {
        $data = $this->input;
        $args['amount'] = $data['amount'];//金额
        $args['user_id'] = $data['user_id'];//用户
        unset($data);
        // 检查用户是否注册
        $memberModel = new LibMember();
        $findRes = $memberModel->findMember(['user_id' => $args['user_id']]);
        if ($findRes['errorCode'] == 1) return Common::errorArray(1, '该用户尚未注册', false);
        if ($findRes['data']['audit_state'] == 0) return Common::errorArray(1, '您的资料正在审核中', false);
        if ($findRes['data']['audit_state'] == 2) return Common::errorArray(1, '您的资料审核未通过', false);
        // 检查用户身份
        $identity_list = explode(',', $findRes['data']['state']);
        if ($identity_list) {
            $identity_list = array_map('intval',$identity_list);
            if (in_array(3, $identity_list)) {
                return Common::errorArray(1, '该用户已经是红娘', false);
            }
            if (in_array(2,$identity_list) && $findRes['data']['vip_open_time'] >= time()) {//是vip且未失效
                return Common::errorArray(1, '您当前的VIP尚未到期，暂不能申请红娘', false);
            }
        }
        // 认证费用
        $configModel = new LibConfig();
        $findRes = $configModel->findConfig(['item_key' => 'matchmaker_auth_fee']);
        $matchmaker_auth_fee = 0;
        if ($findRes['errorCode'] == 0) $matchmaker_auth_fee = $findRes['data']['item_value'];
        if (bccomp($args['amount'], $matchmaker_auth_fee) != 0) return Common::errorArray(1, '金额错误', false);
        $args['amount'] = $matchmaker_auth_fee;
        // 订单参数
        $redMotherAuthOrderModel = new LibOrderRedMother();
        $checkRes = $redMotherAuthOrderModel->goCheck($args);
        if ($checkRes['errorCode'] == 1) return Common::errorArray(1, $checkRes['errorInfo'], false);

        // 分销处理
        $distributeFields = $this->getDistributeField($memberModel, $args, 'red_mother_auth_rate');

        // 创建订单
        $orderModel = new \app\common\model\hfztcy\LibOrder();
        $code = $orderModel->generateOrderNum();
        Db::startTrans();
        try {
            $findOrderRes = $orderModel->findOrder("transaction_id IS NULL AND user_id = {$this->user['id']} AND type = 3");
            if ($findOrderRes['errorCode'] == 0) {
                $order_id = $findOrderRes['data']['id'];
                $orderModel->updateOrder(['id'  => $order_id],[
                    'code' => $code,
                    'type' => 3,
                    'user_id' => $this->user['id'],
                    'exec_state' => 0//待发放的冻结收益
                ]);
            } else {
                $result = $orderModel->addOrder([
                    'code' => $code,
                    'type' => 3,
                    'user_id' => $this->user['id'],
                    'exec_state' => 0//待发放的冻结收益
                ]);
                $order_id = (int)$result['data'];
            }
            $findRedMotherOrderRes = $redMotherAuthOrderModel->findOrder(['order_id' => $order_id,'user_id' => $this->user['id']]);
            if ($findRedMotherOrderRes['errorCode'] == 0) {
                $redMotherAuthOrderModel->updateOrder(['order_id' => $order_id,'user_id' => $this->user['id']],array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'add_time' => Common::getTime(),
                ]));
            } else {
                $redMotherAuthOrderModel->addOrder(array_merge($args, $distributeFields, [
                    'order_id' => $order_id,
                    'add_time' => Common::getTime(),
                ]));
            }
            Db::commit();
            return Common::errorArray(0, '订单创建成功', $order_id);
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1, '订单创建失败' . $exception->getMessage(), false);
        }
    }

    public function updateOrderByRedMotherAuth ($user_id)
    {
        // 认证费用
        $configModel = new LibConfig();
        $findRes = $configModel->findConfig(['item_key' => 'matchmaker_auth_fee']);
        $matchmaker_auth_fee = 0;
        if ($findRes['errorCode'] == 0) $matchmaker_auth_fee = $findRes['data']['item_value'];
        $args['amount'] = $matchmaker_auth_fee;
        $memberModel = new LibMember();
        // 分销处理
        return $this->getDistributeField($memberModel, $args, 'red_mother_auth_rate');
    }
}

?>